package com.mango.httpforward.web.Initializer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONUtil;
import com.mango.httpforward.web.config.ForwardProperties;
import com.mango.httpforward.web.holder.ForwardHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class ForwardHolderInitializer implements InitializingBean {

    private final ForwardProperties forwardProperties;

    private static final String[] EXCLUDE_KEYS = { "proxy" };

    /**
     * 将配置中的参数放置缓存
     */
    @Override
    public void afterPropertiesSet() {
        List<String> excludeKeys = Arrays.asList(EXCLUDE_KEYS);
        Map<String, Field> fieldMap = ReflectUtil.getFieldMap(ForwardProperties.class);
        log.info(JSONUtil.toJsonStr(fieldMap));

        fieldMap.forEach((k, v) -> {
            if(CollUtil.contains(excludeKeys, k)) {
                return;
            }

            Object fieldValue = ReflectUtil.getFieldValue(forwardProperties, v);
            List<ForwardProperties.KvEntry> list = JSONUtil.toList(JSONUtil.toJsonStr(fieldValue), ForwardProperties.KvEntry.class);
            log.info("key = {}, value = {}", k, JSONUtil.toJsonStr(list));

            if(CollUtil.isNotEmpty(list)) {
                Map<String, String> kvMap = new HashMap<>();
                for (ForwardProperties.KvEntry kvEntry : list) {
                    kvMap.put(kvEntry.getKey(), kvEntry.getValue());
                }
                if(MapUtil.isNotEmpty(kvMap)) {
                    ForwardHolder.setForwardMap(k, kvMap);
                }
            }
        });
    }
}
